package com.fzrskj.cloud.free.user.dao;

import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.CloudDbDrvUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountData;
import ms.core.consts.SysErr;
import ms.core.db.IDbDrv;
import ms.core.object.CObject;
import ms.core.tool.StrTool;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserAccountDataDao extends CObject {
    //private declarations
    private IDbDrv db = null;

    //constructor function to initialize database access object
    public UserAccountDataDao() {
        db = CloudDbDrvUtils.getDbUtilsDrv();
    }

    //to free resource
    @Override
    public void dispose() {
        db.closeConnection();
    }

    /**
     * 根据email查询对象
     *
     * @param email
     * @return
     */
    public UserAccountData queryAccountDataByEmail(String email) {
        String sql = "select * from user_accountdata where email=? and agentId=?";
        UserAccountData querUserAccountDataByEmail = db.queryForBean(sql, UserAccountData.class, new Object[]{email, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return querUserAccountDataByEmail;
    }

    /**
     * 根据email查询对象
     *
     * @param userName
     * @return
     */
    public UserAccountData queryAccountDataByName(String userName) {
        String sql = "select * from user_accountdata where userName=? and agentId=?";
        UserAccountData querUserAccountDataByEmail = db.queryForBean(sql, UserAccountData.class, new Object[]{userName, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return querUserAccountDataByEmail;

    }

    /**
     * 根据mobile查询对象
     *
     * @param mobile
     * @return
     */
    public UserAccountData queryAccountDataByMobile(String mobile) {
        String sql = "select * from user_accountdata where mobile=? and agentId=?";
        UserAccountData querUserAccountDataByMobile = db.queryForBean(sql, UserAccountData.class, new Object[]{mobile, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return querUserAccountDataByMobile;
    }

    /**
     * 根据userName删除表
     *
     * @param userName
     * @return
     */
    public int deleteAccountByUserName(String userName) {
        String sql = "delete from user_accountdata where userName=? and agentId=?";
        int ret = db.executeSql(sql, new Object[]{userName, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to add new record to database by map
    public int addUserAccountData(Map<String, Object> values) {
        //if (!values.containsKey("agentId")) {
            values.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.insertRecord("user_accountdata", values);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to delete table record by id
    public int delUserAccountData(int id) {
        String sql = "delete from user_accountdata where id=? and agentId=?";
        int ret = db.executeSql(sql, new Object[]{id, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to delete table record by cdt
    public int delUserAccountdata(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.deleteRecord("user_accountdata", cdt);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    /**
     * update user account detail info
     *
     * @param userName user name
     * @param j        UserAccountData object
     * @return <0 system error; =0 user not exists; >0 success
     */
    public int updateUseData(String userName, JSONObject j) {
        Map<String, Object> cdt = new HashMap<>();
        cdt.put("userName", userName);
        cdt.put("agentId", CloudContextUtils.getAgentId());
        //TODO
        Map<String, Object> values = new HashMap<>();
        values.put("address", j.optString("address"));
        if(j.containsKey("certCode") && !StrTool.isBlankStr("certCode")) {
            values.put("certCode", j.optString("certCode"));
        }
        if (j.containsKey("certType") && !StrTool.isBlankStr(j.getString("certType"))) {
            values.put("certType", j.optString("certType"));
        }
        if (j.containsKey("cityCode") && !StrTool.isBlankStr(j.getString("cityCode"))) {
            values.put("cityCode", j.optString("cityCode"));
        }
        values.put("companyName", j.optString("companyName"));
        values.put("fax", j.optString("fax"));
        values.put("fullName", j.optString("fullName"));
        values.put("industry", j.optString("industry"));
        values.put("mainBusiness", j.optString("mainBusiness"));
        if (j.containsKey("mobile") && !StrTool.isBlankStr(j.getString("mobile")) && j.getString("mobile").indexOf("*") == -1) {
            values.put("mobile", j.optString("mobile"));
        }
        values.put("provinceCode", j.optString("provinceCode"));
        values.put("remark", j.optString("remark"));
        values.put("tel", j.optString("tel"));
        values.put("QQ", j.optString("QQ"));
        values.put("userType", j.optString("userType"));
        if (j.containsKey("email") && !StrTool.isBlankStr(j.getString("email"))) {
            values.put("email", j.optString("email"));
        }

        int ret = db.modifyRecord("user_accountdata", values, cdt);
        this.setErrCode(db.getErrCode());
        return ret;
    }

    //to modify table record by values and condition
    public int modUserAccountdata(Map<String, Object> values, Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.modifyRecord("user_accountdata", values, cdt);
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }

        return ret;
    }

    //to query user_accountdata item for detail
    public UserAccountData queryUserAccountdata(int id) {
        String sql = "select * from user_accountdata where id=? and agentId=?";
        UserAccountData ret = db.queryForBean(sql, UserAccountData.class, new Object[]{id, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to query UserAccountdata record count
    public int queryUserAccountdata(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.queryRecordCount("user_accountdata", cdt);
        this.setErrCode(db.getErrCode());
        return ret;
    }

    //to query UserAccountdata for record list with condition,if page or pagesize less than 0, means without page
    public List<UserAccountData> queryUserAccountdataList(Map<String, Object> cdt, int page, int pagesize) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        List<UserAccountData> ret = db.queryForBeans("user_accountdata", "*", "id desc", UserAccountData.class, cdt, page, pagesize);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    // to query UserAccountdata for record list with condition,if page or pagesize less than 0, means without page
    public List<UserAccountData> queryUserAccountdataList(Map<String, Object> cdt) {
        List<Object> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select * from user_accountdata where 1=1 and agentId=?");
        list.add(CloudContextUtils.getAgentId());
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            sb.append(" and " + c.getKey() + "=? ");
            list.add(c.getValue());

        }
        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        List<UserAccountData> ret = db.queryForBeans(sb.toString(), UserAccountData.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //云主机会员数据
    public List<UserAccountData> queryCloudUadList() {
        StringBuilder sb = new StringBuilder("select ua.* from user_accountdata ua where ua.userId in(select distinct userId from user_service where agentId=?) and ua.agentId=?");
        List<UserAccountData> ret = db.queryForBeans(sb.toString(), UserAccountData.class, new Object[]{CloudContextUtils.getAgentId(), CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //域名会员数据
    public List<UserAccountData> queryDomainUadList() {
        StringBuilder sb = new StringBuilder("select ua.* from user_accountdata ua where ua.userId in(select distinct userId from user_domain where agentId=?) and ua.agentId=?");
        List<UserAccountData> ret = db.queryForBeans(sb.toString(), UserAccountData.class, new Object[]{CloudContextUtils.getAgentId(), CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //消费会员数据
    public List<UserAccountData> queryConsumeUadList() {
        StringBuilder sb = new StringBuilder("select ua.* from user_accountdata ua where ua.userId in(select distinct userId from user_accountdetail where itemId=100 and agentId=?)  and ua.agentId=? ");
        List<UserAccountData> ret = db.queryForBeans(sb.toString(), UserAccountData.class, new Object[]{CloudContextUtils.getAgentId(), CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }
}